package com.suxin.netty.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Tang
 * @classname MyClientHandler
 * @description [ TODO ]
 * @date 2021/1/11 13:23
 */
public class MySimpleClientHandler extends SimpleChannelInboundHandler<ProtocolMessage> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = "hello server! ";
        for (int i = 0; i < 3; i++) {
            ProtocolMessage protocolMessage = new ProtocolMessage();
            protocolMessage.setMsg((msg + i).getBytes());
            protocolMessage.setLen(protocolMessage.getMsg().length);
            System.out.println("len = " + protocolMessage.getLen());
            ctx.writeAndFlush(protocolMessage);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMessage msg) throws Exception {
        System.out.println("client接收到如下消息：");
        System.out.println("msg：" + new String(msg.getMsg()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("client接收到如下消息：");
        if (msg instanceof ProtocolMessage) {
            ProtocolMessage message = (ProtocolMessage) msg;
            System.out.println("msg：" + new String(message.getMsg()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

}